package com.control.qct.businesssteward.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.control.qct.businesssteward.R;
import com.control.qct.businesssteward.activity.PaymentActivity;
import com.control.qct.businesssteward.adapter.PaymentDetailAdapter;
import com.control.qct.businesssteward.adapter.PaymentStyleAdapter;
import com.control.qct.businesssteward.base.BaseBean;
import com.control.qct.businesssteward.base.BaseFragment;
import com.control.qct.businesssteward.httputils.HttpUtils;
import com.control.qct.businesssteward.model.PaymentDetailModel;
import com.control.qct.businesssteward.model.PaymentResultModel;
import com.control.qct.businesssteward.model.PaymentStyleModel;
import com.control.qct.businesssteward.utils.DecimalFormatUtils;
import com.control.qct.businesssteward.utils.DialogUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.control.qct.businesssteward.utils.GsonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 结算界面2--支付方式选择
 * Created by Administrator on 2017/12/3 0003.
 */

public class PaymentStyleFragment extends BaseFragment implements PaymentScanFragment.IPaymentCallbackResult {
    @BindView(R.id.tv_receivable_all)
    TextView mTvReceivableAll;//应收总金额
    @BindView(R.id.tv_not_receivable)
    TextView mTvNotReceivable;//未收金额
    @BindView(R.id.rv_pay_style)
    RecyclerView mRvPayStyle;//支付方式列表
    @BindView(R.id.rv_pay_detail)
    RecyclerView mRvPayDetail;//支付详情列表
    @BindView(R.id.tv_buyer_credit)
    TextView mTvBuyerCredit;//挂账
    @BindView(R.id.tv_sure)
    TextView mTvSure;//确定

    private View mPayStyleView;//支付方式布局
    List<PaymentStyleModel> mPaymentStyleModelList = new ArrayList<>();
    ;//支付方式集合
    private PaymentStyleAdapter mPaymentStyleAdapter;//支付方式适配器
    private Dialog mPayStyleDialog;//支付方式弹窗
    private TextView mTvPayStyleName;//支付方式弹窗--支付方式名称
    private EditText mEtPayCash;//支付方式弹窗--收款金额
    private LinearLayout mLlCashCoupon;//支付方式弹窗--现金券父控件
    private EditText mEtCouponMemberNum;//支付方式弹窗--现金券号或会员号
    private TextView mTvAbleCashCoupon;//支付方式弹窗--现金券可用余额

    List<PaymentDetailModel> mPaymentDetailModelList = new ArrayList<>();//付款明细集合
    private PaymentDetailAdapter mPaymentDetailAdapter;//付款明细适配器
    private String mPayStyleName;//付款方式名称
    private double mCash;//付款金额
    private PaymentActivity mPaymentActivity;
    private double mOrderAmount;//应收金额
    private double mNotPayAmount;//未收金额
    private double mPayAmount;//已收金额
    private int imageId;
    private PaymentResultModel mPaymentResultModel;
    private List<PaymentResultModel.PayResultsBean> mPayResultsBeanList = new ArrayList<>();
    private Map<String, String> mParams;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mPaymentActivity = (PaymentActivity) context;
    }

    @Override
    protected View initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        return inflater.inflate(R.layout.fragment_payment_style, container, false);
    }


    @Override
    protected void initView(View view) {
        activity.setLeftIcon(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.finish();
            }
        });
        //设置应收
        mOrderAmount = mPaymentActivity.mDoPayGoodsModel.getOrderAmount();
        mTvReceivableAll.setText("￥" + DecimalFormatUtils.DecimalFormatTwo(mOrderAmount));
        //如果已经请求过网络获取支付方式   则不在请求
        if (mPaymentStyleModelList.size() == 0) {
            getPayStyleList();
        }
        mRvPayStyle.setLayoutManager(new GridLayoutManager(activity, 4));
        mPaymentStyleAdapter = new PaymentStyleAdapter(mPaymentStyleModelList);
        mRvPayStyle.setAdapter(mPaymentStyleAdapter);
        mPaymentStyleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (mPaymentStyleAdapter.getData().get(position).getGroupNo()) {
                    case 2://支付宝
                        getPayResult(24, mPaymentStyleAdapter.getData().get(position));
                        break;
                    case 4://智能码
                        getPayResult(18, mPaymentStyleAdapter.getData().get(position));
                        break;
                    case 6://微信
                        getPayResult(26, mPaymentStyleAdapter.getData().get(position));
                        break;
                    case 1://现金
                        setPayStyleDialog(mPaymentStyleAdapter.getData().get(position));
                        break;
                    default:
                        showShortToast("该支付方式暂未开通，请选择其他方式支付！");
                        break;
                }
            }
        });
        mRvPayDetail.setLayoutManager(new LinearLayoutManager(activity));
        mPaymentDetailAdapter = new PaymentDetailAdapter(mPaymentDetailModelList);
        mRvPayDetail.setAdapter(mPaymentDetailAdapter);
        mPayAmount = 0;
        for (int i = 0; i < mPaymentDetailModelList.size(); i++) {
            mPayAmount += mPaymentDetailModelList.get(i).getCash();
        }
        // 设置未收金额
        mNotPayAmount = mOrderAmount - mPayAmount;
        mTvNotReceivable.setText("￥" + DecimalFormatUtils.DecimalFormatTwo(mNotPayAmount));
    }

    /**
     * 获取支付方式列表
     */
    private void getPayStyleList() {
        mNetProtocol.getPayList(activity, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                List<PaymentStyleModel> models = (List<PaymentStyleModel>) baseBean.getData();
                mPaymentStyleModelList.addAll(models);
                if (mPaymentStyleAdapter != null) {
                    mPaymentStyleAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });
    }

    @OnClick({R.id.tv_buyer_credit, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_buyer_credit://挂账
                break;
            case R.id.tv_sure://确认
                if (mNotPayAmount > 0) {
                    showShortToast("未完成支付，请继续支付！");
                    return;
                }
                finishOrder();
                break;
        }
    }

    /**
     * 支付方式弹窗
     */
    private void setPayStyleDialog(final PaymentStyleModel paymentStyleBeans) {
        mPayStyleView = View.inflate(activity, R.layout.dialog_select_pay_style, null);
        mPayStyleDialog = DialogUtil.getDialog(activity, mPayStyleView, true);
        mTvPayStyleName = mPayStyleView.findViewById(R.id.tv_pay_style_name);
        mEtPayCash = mPayStyleView.findViewById(R.id.et_pay_cash);
        mLlCashCoupon = mPayStyleView.findViewById(R.id.ll_cash_coupon);
        mEtCouponMemberNum = mPayStyleView.findViewById(R.id.et_coupon_member_num);
        mTvAbleCashCoupon = mPayStyleView.findViewById(R.id.tv_able_cash_coupon);
        if (mNotPayAmount != 0) {
            mEtPayCash.setText(DecimalFormatUtils.DecimalFormatTwo(mNotPayAmount));
            mEtPayCash.setSelection(mEtPayCash.length());
        }
        mPayStyleView.findViewById(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(mEtPayCash.getText().toString())) {
                    showShortToast("请输入收款金额！");
                    return;
                }
                if (mNotPayAmount == 0) {
                    showShortToast("已完成支付，无需再支付！");
                    return;
                }
                mCash = Double.parseDouble(mEtPayCash.getText().toString());
                if (mCash <= 0) {
                    showShortToast("支付金额必须大于0，请重新输入！");
                    return;
                }
                if (mCash > mNotPayAmount) {
                    showShortToast("支付金额大于未收金额，请重新输入！");
                    return;
                }
                switch (paymentStyleBeans.getGroupNo()) {
                    case 1://现金
                        imageId = R.drawable.icon_jiesuan_xianjin;
                        setPayResult("", 11);
                        break;
                    case 2://支付宝
                        imageId = R.drawable.icon_jiesuan_zhifubao;
                        activity.replaceFragment(R.id.fl_content, new PaymentScanFragment(mPaymentActivity
                                .mDoPayGoodsModel, paymentStyleBeans, mCash, PaymentStyleFragment.this), true);
                        break;
                    case 4://智能码
                        imageId = R.drawable.icon_shouyintai_yimafu;
                        activity.replaceFragment(R.id.fl_content, new PaymentScanFragment(mPaymentActivity
                                .mDoPayGoodsModel, paymentStyleBeans, mCash, PaymentStyleFragment.this), true);
                        break;
                    case 6://微信
                        imageId = R.drawable.icon_jiesuan_weixin;
                        activity.replaceFragment(R.id.fl_content, new PaymentScanFragment(mPaymentActivity
                                .mDoPayGoodsModel, paymentStyleBeans, mCash, PaymentStyleFragment.this), true);
                        break;
                    case 3://储值卡
                        imageId = R.drawable.icon_jiesuan_chuzhika;
                        setPayResult("", 16);
                        break;
                    case 5://抵用券
                        imageId = R.drawable.icon_jiesuan_diyongquan;
                        setPayResult("", 15);
                        break;
                    case 7://购物卡
                        imageId = R.drawable.icon_jiesuan_gouwuka;
                        setPayResult("", 14);
                        break;
                    case 8://云闪付
                        imageId = R.drawable.icon_jiesuan_yunshanfu;
                        setPayResult("", 12);
                        break;
                    case 9://积分抵扣
                        imageId = R.drawable.icon_jiesuan_jifen;
                        setPayResult("", 13);
                        break;
                }
                mPayStyleDialog.dismiss();
            }
        });
        mPayStyleView.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPayStyleDialog.dismiss();
            }
        });
        mPayStyleName = paymentStyleBeans.getTitle();
        mLlCashCoupon.setVisibility(paymentStyleBeans.getGroupNo() == 5 ? View.VISIBLE : View.GONE);
        mTvPayStyleName.setText(mPayStyleName);
    }


    /**
     * 获取支付被扫结果
     */
    private void getPayResult(final int payType, final PaymentStyleModel paymentStyleBeans) {
        mParams = new HashMap<>();
        mParams.put("orderId", mPaymentActivity.mDoPayGoodsModel.getOrderId());
        mParams.put("payType", payType + "");
        mNetProtocol.getPayResult(activity, mParams, true, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                if (((Double) baseBean.getData()) == 1) {
                    showShortToast("该支付方式已用，请选择其他方式支付！");
                } else {
                    switch (payType) {
                        case 18:
                        case 24:
                        case 26:
                            setPayStyleDialog(paymentStyleBeans);
                            break;
                    }
                }
            }

            @Override
            public void onFail(BaseBean baseBean) {

            }
        });
    }


    /**
     * 订单完成
     */
    private void finishOrder() {
        mPaymentResultModel = new PaymentResultModel();
        mPaymentResultModel.setOrderId(mPaymentActivity.mDoPayGoodsModel.getOrderId());
        mPaymentResultModel.setOrderSn(mPaymentActivity.mDoPayGoodsModel.getOrderSn());
        mPaymentResultModel.setMemberId(mSPUtils.getString("member_id"));
        mPaymentResultModel.setPayResults(mPayResultsBeanList);
        String result = GsonUtil.GsonString(mPaymentResultModel);
        mNetProtocol.finishOrder(activity, result, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                //订单完成后  清除保存的会员id
                mSPUtils.remove("member_id");
                showShortToast("结算成功！");
                activity.setResult(Activity.RESULT_OK);
                activity.finish();
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });

    }


    @Override
    public void onResult(String tradeNo, int payType) {
        setPayResult(tradeNo, payType);
    }


    /**
     * 支付结果 金额计算
     */
    private void setPayResult(String tradeNo, int payType) {
        mNotPayAmount -= mCash;
        String s = DecimalFormatUtils.DecimalFormatTwo(mNotPayAmount);
        if (mTvNotReceivable != null)
            mTvNotReceivable.setText("￥" + DecimalFormatUtils.DecimalFormatTwo(mNotPayAmount));
        mPaymentDetailModelList.add(new PaymentDetailModel(imageId, mPayStyleName, mCash));
        mPayResultsBeanList.add(new PaymentResultModel.PayResultsBean(1, false, mCash, payType, tradeNo, ""));
        mPaymentDetailAdapter.notifyDataSetChanged();
    }
}
